package com.demo.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

/**
 * gzip压缩
 *
 * @author lee9213@163.com
 * @version 1.0
 * @date 2017/3/21 13:41
 */
public class GzipUtil {

    public static byte[] gzip(byte[] data) {
        ByteArrayOutputStream bos = null;
        GZIPOutputStream gzip = null;
        try {
            bos = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(bos);
            gzip.write(data);
            gzip.finish();
            byte[] bytes = bos.toByteArray();
            return bytes;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (gzip != null) gzip.close();
                if (bos != null) bos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static byte[] ungzip(byte[] data) {
        ByteArrayInputStream bis = null;
        GZIPInputStream gzip = null;
        ByteArrayOutputStream baos = null;
        try {
            bis = new ByteArrayInputStream(data);
            gzip = new GZIPInputStream(bis);
            byte[] bytes = new byte[1024];
            int num = -1;
            baos = new ByteArrayOutputStream();
            while ((num = gzip.read(bytes, 0, bytes.length)) != -1) {
                baos.write(bytes, 0, num);
            }
            byte[] b = baos.toByteArray();
            return b;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (gzip != null) gzip.close();
                if (bis != null) bis.close();
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
